<template>
  <div>
  <el-table :data="filterTableData"
            border style="width: 100%"
            :key="updateKey"
            :default-sort="{ prop: 'date', order: 'descending' }">
    <el-table-column label="提交日期" prop="date" sortable width="180"/>
    <el-table-column label="论文题目" prop="name" />
    <el-table-column label="作者" prop="author"/>
    <el-table-column label="状态" prop="state"></el-table-column>
    <!--    <el-table-column label="状态"-->
    <!--                      prop="tag"-->
    <!--                     :filters="[{text:'a',value:'a'},{text:'b',value:'b'}]"-->
    <!--                     :filter-method="filterTag"-->
    <!--                     filter-placement="bottom-end"-->
    <!--    >-->
    <!--      <template #default="scope1">-->
    <!--        <el-tag-->
    <!--        :type="scope1.row.tag==='a'?'':'success'"-->
    <!--        disable-transitions-->
    <!--        >{{scope1.row.tag}}</el-tag>-->
    <!--      </template>-->
    <!--    </el-table-column>-->
    <el-table-column label="分数" prop="score" />
    <el-table-column align="center">
      <template #header style="text-align: center">
        <el-input v-model="input" size="small" placeholder="输入文章题目/作者" style="width: 80%;justify-content: start"/>
        <el-button size="small"  type="primary" @click="searchFind" style="width: 20%;justify-content: end">搜索</el-button>
      </template>
      <template #default="scope" >

        <!--修改论文-->
        <el-button  size="small" @click="dialogFormVisible = true; setFocus(scope.row)" >批改</el-button>&nbsp;
        <!--查看-->
        <el-button size="small" @click=" setFocus(scope.row); go();" type="info" >查看</el-button>
        <br>
        <!--下载-->

        <el-button size="small" @click="download(scope.row)">下载</el-button>&nbsp;
        <!--删除-->
        <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <div class="demo-pagination-block">
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10,14, 20, 50]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="sizes, prev, pager, next"
        :total="totalPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
  <!--修改弹窗-->
  <el-dialog v-model="dialogFormVisible" title="论文修改">
    <!--    <div class="container" title="审核">-->
    <!--      <h style="font-weight: bold">审核：</h>-->
    <!--      <el-form>-->
    <!--        <el-form-item label="审核状态：">-->
    <!--          <el-select v-model="statusValue" clearable placeholder="选择审核状态">-->
    <!--            <el-option-->
    <!--                v-for="item in options"-->
    <!--                :key="item.value"-->
    <!--                :label="item.label"-->
    <!--                :value="item.value"-->
    <!--            />-->
    <!--          </el-select>-->
    <!--        </el-form-item>-->
    <!--        <el-form-item label="审核理由：">-->
    <!--          <el-input-->
    <!--              v-model="textarea"-->
    <!--              maxlength="200"-->
    <!--              placeholder="请输入通过/驳回的原因"-->
    <!--              show-word-limit-->
    <!--              type="textarea"-->
    <!--          />-->
    <!--        </el-form-item>-->
    <!--        <el-button type="primary" size="large" style="position: relative;left: 19.5%" @click="submitStatus">提交</el-button>-->
    <!--      </el-form>-->
    <!--    </div>-->
    <div class="container" title="批改">
      <h style="font-weight: bold">批改：</h>
      <el-form >
        <el-form-item label="论文分数："  >
          <el-input-number size="large" v-model="num" :min="0" :max="100" @change="handleChange" />
        </el-form-item>
        <el-button type="primary" size="large" style="position: relative;left: 19.5%" @click="dialogFormVisible=false;submitSCore(this)">提交</el-button>
      </el-form>
    </div>
  </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {reactive, computed, ref, toRaw} from 'vue'
import {ElMessage, genFileId, UploadInstance, UploadProps, UploadRawFile, ElTable} from "element-plus";
import axios from "axios";
import assert from "assert";
import router from "../router";

interface User {
  id: number
  date: string
  name: string
  state:string
  score:number
  author:string
  tag:string
}
const Correction = reactive({
  "score": "number",
})
//论文审核
const statusValue = ref('')
const options = [
  {
    value: 'Option1',
    label: '通过',
  },
  {
    value: 'Option2',
    label: '驳回',
  },

]
//理由
const textarea = ref('')
//

const dialogFormVisible = ref(false)
const num = ref(0)
const handleChange = (value: number) => {
  console.log(value)
}
const formLabelWidth = '140px'
const search = ref('')
const input =ref("")
const filterTableData = computed(() =>
    tableData.filter(
        (data) =>
            !search.value ||
            data.name.toLowerCase().includes(search.value.toLowerCase())
    )
)
const go = () => {
  router.push ({
    path:"/display",
    query:{
      paperId: selectedID.value
    }
  });
}
const handleDelete = (index: number, row: User) => {
  confirm("该操作不可恢复，是否继续？");
  console.log(index, row)
  let item = toRaw(row)
  axios.get(`paper/delete?paperId=${item.id}`,
      {
        headers: {
          'Content-Type': 'application/json',
          'session': localStorage.getItem('ID'),
        }
      }).then(res => {
    if (res.data.code === 0) {
      set();
      ElMessage('删除成功');
      router.push('/editor');
    } else {
      ElMessage('删除失败');
    }
  })
}
const upload = ref<UploadInstance>()
const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  upload.value!.handleStart(file)
}
const tableData = reactive<User[]>([])
let updateKey = ref(1)
let currentPage = ref(1)
let pageSize = ref(14)
let totalPage = ref(50)
const small = ref(false)
const background = ref(true)
const disabled = ref(false)

const set = ()=> {
  axios.get(`paper/listForAdmin?pageSize=${pageSize.value}&pageNum=${currentPage.value}`,
      {
        headers: {
          'Content-Type': 'application/json',
          'session': localStorage.getItem('ID'),
        }
      }).then(res => {
    if (res.data.code === 0) {
      while (tableData.length != 0) tableData.pop();
      totalPage.value =res.data.data.total;

      console.log(tableData);
      res.data.data.list.forEach(function (e) {
          let user: User = {
            id: e.id,
            date: e.uploadTime.split(' ')[0],
            name: e.title,
            author:e.authorOneName,
            state: e.status===1?"通过":(e.status===0?"审核中":"不通过"),
            score: e.score,
          };
          tableData.push(user);

      })

      console.log(res);
      //totalPage.value =res.data.data.total;
      console.log(res.data.data.pageNum);
      console.log(res.data.data.pages);
      // updateKey.value += 1;
      console.log('current page '+currentPage.value)
      console.log(filterTableData);
    } else {
      ElMessage('切换失败');
    }
  })
}
set()
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  console.log(currentPage);
  axios.get(`paper/listForAdmin?pageSize=${val}&pageNum=${1}`,
      {
        headers:{
          'Content-Type': 'application/json',
          'session':localStorage.getItem('ID'),
        }
      }).then(res=>{
    console.log(tableData);
    if(res.data.code === 0) {
      while(tableData.length != 0) tableData.pop();
      totalPage.value =res.data.data.total;
      console.log(tableData);
      res.data.data.list.forEach(function (e){

            let user: User = {
              id: e.id,
              date: e.uploadTime.split(' ')[0],
              name: e.title,
              author:e.authorOneName,
              state: e.status===1?"通过":(e.status===0?"审核中":"不通过"),
              score: e.score,
            };
            tableData.push(user);

      })
      currentPage = res.data.pageNum;
      // updateKey.value += 1;
      console.log(filterTableData);
    }else {
      ElMessage('切换失败');
    }
  })
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)

  axios.get(`paper/listForAdmin?pageSize=${pageSize.value}&pageNum=${val}`,
      {
        headers:{
          'Content-Type': 'application/json',
          'session':localStorage.getItem('ID'),
        }
      }).then(res=>{
    console.log(tableData);
    if(res.data.code === 0) {
      while(tableData.length != 0) tableData.pop();

      console.log(tableData);
      res.data.data.list.forEach(function (e){

          let user: User = {
            id: e.id,
            date: e.uploadTime.split(' ')[0],
            name: e.title,
            author:e.authorOneName,
            state: e.status===1?"通过":(e.status===0?"审核中":"不通过"),
            score: e.score,
          };
          tableData.push(user);

      })
      totalPage.value =res.data.data.total;
      currentPage = res.data.pageNum;
      // updateKey.value += 1;
      console.log(filterTableData);
    }else {
      ElMessage('切换失败');
    }
  })
}
const downloadAttach = (flag: string, title:string) => {
  // 发送get请求
  console.log(flag)
  axios.get(`/paper/download/${flag}`, {
    headers: {
      'Content-Type': 'application/json',
      'session':localStorage.getItem('ID'),
    },
    responseType: 'blob'
  })
      .then(res => {
        const blob = new Blob([res.data]);//处理文档流
        const file = res.headers['content-disposition'];
        console.log(res);
        const fileName = `${title}.pdf`;
        const down = document.createElement('a');
        down.download = fileName;
        down.style.display = 'none';
        down.href = URL.createObjectURL(blob);
        document.body.appendChild(down);
        down.click();
        URL.revokeObjectURL(down.href);
        document.body.removeChild(down);
      })
      .catch(() => {
        alert("请求出错");
      })
  // alert(url);
}
const download = (row: any) => {
  console.log(row)
  let item = toRaw(row);
  console.log(item);
  axios.get(`paper?paperId=${item.id}`,
      {
        headers:{
          'Content-Type': 'application/json',
          'session':localStorage.getItem('ID'),
        }
      }).then(res=>{
    if(res.data.code === 0) {
      console.log(res.data);
      let length = res.data.data.filePath.toString().split('/').length;
      let flag = res.data.data.filePath.toString().split('/')[length-1];
      console.log(flag);

      downloadAttach(flag, item.name)
    }else {
      console.log("获取flag出错")
      ElMessage('下载失败');
    }
  })
}
const searchFind = ()=>{
  if(input.value===""){
    set();
    return;
  }
  axios.get(`/paper/search?content=${input.value}&pageNum=${currentPage.value}&pageSize=${pageSize.value}`,
      {
        headers:{
          'Content-Type': 'application/json',
          'session': localStorage.getItem('ID'),
        }
      }).then(res=>{
    if(res.data.code===0)
    {
      while (tableData.length != 0) tableData.pop();
      console.log(tableData);
      res.data.data.list.forEach(function (e) {

          let user: User = {
            id: e.id,
            date: e.uploadTime.split(' ')[0],
            name: e.title,
            author:e.authorOneName,
            state: e.status===1?"通过":(e.status===0?"审核中":"不通过"),
            score: e.score,
          };
          tableData.push(user);

      })
      console.log(res);
      totalPage.value =res.data.data.total;
      console.log(res.data.data.pageNum);
      // updateKey.value += 1;
      console.log('current page '+currentPage.value)
      console.log(filterTableData);
    }
    else{
      ElMessage('搜索失败');
    }
  })
}
let selectedID = ref(0)
const setFocus = (row:User) => {
  console.log(row);
  selectedID = ref(row.id);
  console.log(selectedID.value);
}

const submitSCore = () =>{
  let paperID:number = selectedID.value;
  axios.get(`/paper/score?paperId=${paperID}&score=${num.value}`,{
    headers:{
      'Content-Type': 'application/json',
      'session':localStorage.getItem('ID'),
    }
  }).then(res=>{
    if(res.data.code === 0)
    {
      ElMessage('提交成功');
      set()

    }
    else {
      ElMessage(res.data.commonErrorCode.errorSuggestion);
    }
  })
}





</script>
<style scoped>
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>